package com.honglang.mail.impl;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.SendFailedException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import com.honglang.common.tools.Constants;

public class MailSender {
	

	 private static final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory"; 
	
	
	 public Properties getGmailProperties(String host){
		 	
		 	Properties props = System.getProperties();   

	        props.setProperty("mail.smtp.host", host);   

	        // Gmail提供的POP3和SMTP是使用安全套接字层SSL的   

	        props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);   

	        props.setProperty("mail.smtp.socketFactory.fallback", "false");   

	        props.setProperty("mail.smtp.port", "465");   

	        props.setProperty("mail.smtp.socketFactory.port", "465");   

	        props.setProperty("mail.imap.socketFactory.class", SSL_FACTORY);   

	        props.setProperty("mail.imap.socketFactory.fallback", "false");   

	        props.setProperty("mail.imap.port", "993");   

	        props.setProperty("mail.imap.socketFactory.port", "993");   

	        props.setProperty("mail.pop3.socketFactory.class", SSL_FACTORY);   

	        props.setProperty("mail.pop3.socketFactory.fallback", "false");   

	        props.setProperty("mail.pop3.port", "995");   

	        props.setProperty("mail.pop3.socketFactory.port", "995");   

	        props.put("mail.smtp.auth", "true");   

	        return props;   

	 }
	 
	 
	 
	 public Message createMessage(final String username,final String password ,String subject,String receiver,String content){
		 	Session session = Session.getDefaultInstance(this.getGmailProperties(Constants.GMAIL_HOST),   
	                new Authenticator() {   
	                    protected PasswordAuthentication getPasswordAuthentication() {   
	                        return new PasswordAuthentication(username, password);   
	                    }   
	               });
		 	
		 	try {
		 		Message msg = new MimeMessage(session);   
				msg.setFrom(new InternetAddress(username));
				InternetAddress[] address = {new InternetAddress(receiver)};
				msg.setRecipients(Message.RecipientType.TO, address);
				msg.setSubject(subject);
				msg.setSentDate(new Date());
				msg.setText(content);
				return msg;   
			} catch (AddressException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return null;
			} catch (MessagingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return null;
			}
		 	
			
		 
	 }
	 
	 
	 public Message createMessage(final String username,final String password ,String receiver,String subject,String content,List<String> fileList){
		 	Session session = Session.getDefaultInstance(this.getGmailProperties(Constants.GMAIL_HOST),   
	                new Authenticator() {   
	                    protected PasswordAuthentication getPasswordAuthentication() {   
	                        return new PasswordAuthentication(username, password);   
	                    }   
	               });
		   
		 	try {
		 		Message msg = new MimeMessage(session); 
				msg.setFrom(new InternetAddress(username));
				InternetAddress[] address = {new InternetAddress(receiver)};
				msg.setRecipients(Message.RecipientType.TO, address);
				msg.setSubject(subject);
				msg.setSentDate(new Date());
				msg.setText(content);
				msg.setContent(this.createMimeMultipart(content, fileList));
				return msg;   
			} catch (AddressException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return null;
			} catch (MessagingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return null;
			}
		 	
			
		 
	 }
	 
	 
	 protected Multipart createMimeMultipart(String conent,List<String> fileList){
		 Multipart mp = new MimeMultipart();	
		 MimeBodyPart mbpContent = new MimeBodyPart();
		 try {
			mbpContent.setText(conent);
			mp.addBodyPart(mbpContent);
			for(String fileName:fileList){
				 MimeBodyPart mbp = new MimeBodyPart();
				    // attach the file to the message
				 mbp.attachFile(fileName);
				 mp.addBodyPart(mbp);
			}
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		 
		 return mp;
	 }
	 
	 
	 
	 
	 public String sendMessage(Message msg){
		 if(null != msg){
			 try {
		
				Transport.send(msg);
			 } catch (MessagingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				Exception ex = e;
				StringBuffer sb = new StringBuffer();
			    do {
				if (ex instanceof SendFailedException) {
				    SendFailedException sfex = (SendFailedException)ex;
				    Address[] invalid = sfex.getInvalidAddresses();
				    if (invalid != null) {
						sb.append("    ** Invalid Addresses");
						if (invalid != null) {
						    for (int i = 0; i < invalid.length; i++) 
						    	sb.append("         " + invalid[i]);
						}
				    }
				    
				    Address[] validUnsent = sfex.getValidUnsentAddresses();
				    if (validUnsent != null) {
						sb.append("    ** ValidUnsent Addresses");
						if (validUnsent != null) {
						    for (int i = 0; i < validUnsent.length; i++) 
						    	sb.append("         "+validUnsent[i]);
						}
				    }
				    Address[] validSent = sfex.getValidSentAddresses();
				    if (validSent != null) {
				    	sb.append("    ** ValidSent Addresses");
						if (validSent != null) {
						    for (int i = 0; i < validSent.length; i++) 
						    	sb.append("         "+validSent[i]);
						}
				    }
				}
				if (ex instanceof MessagingException)
				    ex = ((MessagingException)ex).getNextException();
				else
				    ex = null;
			    } while (ex != null);
			    return sb.toString();
			}
			return "password.send.success";
		 }else{
			return "Message is null";
		 }
		 
		
	 }
	
	 
	 public static void main(String[] args){
		 MailSender mailSender  = new MailSender();
		 mailSender.sendMessage(mailSender.createMessage("honglangqq@gmail.com", "76962651985", "Java Test", "honglangqq@gmail.com", "Hi,我是中国人"));
	 }
	
}
